package com.wuuxiang.polestar.admin.web;

import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.wuuxiang.polestar.admin.dto.BaseReturnDTO;
import com.wuuxiang.polestar.admin.dto.ConfigDto;
import com.wuuxiang.polestar.admin.service.property.IPropertyService;
import com.wuuxiang.polestar.admin.service.propertyitem.IPropertyItemService;
import com.wuuxiang.polestar.comm.constant.Constant;
import com.wuuxiang.utils.string.StrUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 项目名称：polestar        <br>
 * 类描述：                         <br>
 * 创建人：夏鸿鹏                    <br>
 * 创建时间：2017-11-29 18:44        <br>
 * 修改备注：                        <br>
 */
@RestController
public class UploadController {

    @Autowired
    private IPropertyService propertyService;
    @Autowired
    private IPropertyItemService propertyItemService;

    @PostMapping("/polestar/uploadPropertyItems")
    public BaseReturnDTO uploadPropertyItems(@RequestParam("upFile") MultipartFile multipartFile, @RequestParam("teamName") String teamName) throws Exception {

        BaseReturnDTO baseReturnDTO = new BaseReturnDTO();
        if (multipartFile.isEmpty()) {
            baseReturnDTO.setReturnCode(-1);
            baseReturnDTO.setErrorCode("500");
            baseReturnDTO.setErrorText("文件不可为空!");
            return baseReturnDTO;
        }
        if (StrUtils.isBlank(teamName)) {
            baseReturnDTO.setReturnCode(-1);
            baseReturnDTO.setErrorCode("500");
            baseReturnDTO.setErrorText("项目组不可为空!");
            return baseReturnDTO;
        }

        String fileName = multipartFile.getOriginalFilename();
        String propertyName = Files.getNameWithoutExtension(fileName);
        InputStream inputstream = multipartFile.getInputStream();

        if (propertyService.checkExists(teamName.trim(), propertyName)) {
            baseReturnDTO.setReturnCode(-1);
            baseReturnDTO.setErrorCode("500");
            baseReturnDTO.setErrorText("配置文件已经存在!");
            return baseReturnDTO;
        }
        savePropertyGroup(teamName.trim(), propertyName, inputstream);
        return baseReturnDTO;
    }
    
	@PostMapping("/polestar/uploadAll")
	public BaseReturnDTO uploadAll(@RequestParam("upFile") MultipartFile multipartFile) throws Exception {
		BaseReturnDTO baseReturnDTO = new BaseReturnDTO();
		if (multipartFile.isEmpty()) {
			baseReturnDTO.setReturnCode(-1);
			baseReturnDTO.setErrorCode("500");
			baseReturnDTO.setErrorText("文件不可为空!");
			return baseReturnDTO;
		}
		String fileExtension = Files.getFileExtension(multipartFile.getOriginalFilename());
		if (Constant.FILE_TYPE_ZIP.equalsIgnoreCase(fileExtension)) {
			InputStream inputstream = multipartFile.getInputStream();
			ZipInputStream zipInputStream = new ZipInputStream(inputstream);
			ZipEntry zipEntry;
			while ((zipEntry = zipInputStream.getNextEntry()) != null) {
				if(zipEntry.isDirectory()) {
					continue;
				}
				Iterable<String> parts = FILE_SPLITTER.split(zipEntry.getName());
				if (Iterables.size(parts) != 2) {
					continue;
				}
				String teamName = Iterables.getFirst(parts, "");
				String fileName = Iterables.getLast(parts, "");
				savePropertyGroup(teamName, Files.getNameWithoutExtension(fileName), zipInputStream);
			}
		} else {
			baseReturnDTO.setReturnCode(-1);
			baseReturnDTO.setErrorCode("500");
			baseReturnDTO.setErrorText("不支持的上传文件类型!");
			return baseReturnDTO;
		}
		return baseReturnDTO;
	}

    private void savePropertyGroup(String teamName, String propertyName, InputStream inputstream) throws IOException {
        List<ConfigDto> items = parseInputFile(teamName, propertyName, inputstream);
        if (!items.isEmpty()) {
            for (ConfigDto item : items) {
                propertyItemService.createPropertyItem(teamName, propertyName, item.getItemName(), item.getValue(), item.getRemark(),false);
            }
        }
    }

    private List<ConfigDto> parseInputFile(String teamName, String propertyName, InputStream inputstream) throws IOException {
        List<String> lines = IOUtils.readLines(inputstream, Charsets.UTF_8.name());
        List<ConfigDto> items = Lists.newArrayList();
        String previousLine = null;
        for (int i = 0; i < lines.size(); i++) {
            String line = lines.get(i);
            if (!line.startsWith("#")) {
                Iterable<String> parts = PROPERTY_SPLITTER.split(line);
                if (Iterables.size(parts) == 2) {
                    ConfigDto item = new ConfigDto(teamName, propertyName, Iterables.getFirst(parts, null).trim(), Iterables.getLast(parts).trim());
                    if (previousLine != null && previousLine.startsWith("#")) {
                        item.setRemark(StringUtils.trimLeadingCharacter(previousLine, '#').trim());
                    }
                    items.add(item);
                }
            }
            previousLine = line;
        }
        return items;
    }

    private Splitter PROPERTY_SPLITTER = Splitter.on('=').limit(2);
    private Splitter FILE_SPLITTER = Splitter.on('/').limit(2);
}
